import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/pages/model_home.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/http/http_export.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/utils/permisson/permission_utils.dart';
import 'package:flutter_yn_goods/utils/push_notification_service.dart';
import 'package:flutter_yn_goods/widgets/widget_share_dialog.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomeLogic extends GetxController {
  RefreshController refreshController = RefreshController(initialRefresh: true);

  int page = 1;
  int limit = 20;

  Rx<ModelHome> homeModelRx = Rx(ModelHome());
  RxInt carouselIndex = 0.obs;

  // Rx<ModelHome> homeModel1Rx = Rx(ModelHome());

  // ScrollController scrollController = ScrollController();
  // var appBarOpacity = 0.0.obs;

  @override
  void onReady() {
    super.onReady();
    // 检查推送权限
    checkPushNotificationPermission();
  }

  @override
  void onInit() {
    super.onInit();
    // scrollController.addListener(addScrollListener);
  }

  /// 复制用户ID
  void copyId() {
    final user = AppUserManager().user.value;
    if (user != null && user.id != null) {
      Clipboard.setData(ClipboardData(
          text: '${AppUserManager().isLeader() ? LocaleKeys.agent_id.tr : LocaleKeys.member_id.tr}:${user.id}'));
      LoadingUtils.showToast(LocaleKeys.copy_success.tr);
    }
  }

  /// 检查推送通知权限
  Future<void> checkPushNotificationPermission() async {
    if (GetPlatform.isIOS) {
      if (await PermissionUtils.checkPermission(Permission.notification)) {
        final token = await PushNotificationService().getPushToken();
        clog('用户授予推送权限，Token: $token', tag: 'PushNotification');
      }
    }

    // try {
    //   final hasPermission = await PushNotificationService().checkAndRequestNotificationPermission();
    //   if (hasPermission) {
    //     // 如果有权限，获取推送 token
    //     final token = await PushNotificationService().getPushToken();
    //     clog('推送权限已授予，Token: $token', tag: 'PushNotification');
    //   } else {
    //     // 如果没有权限，显示权限请求对话框
    //     final granted = await PushNotificationService().showPermissionRequestDialog();
    //     if (granted) {
    //       // 如果用户同意授权，获取推送 token
    //       final token = await PushNotificationService().getPushToken();
    //       clog('用户授予推送权限，Token: $token', tag: 'PushNotification');
    //     } else {
    //       clog('用户拒绝推送权限', tag: 'PushNotification');
    //     }
    //   }
    // } catch (e) {
    //   clog('检查推送权限时出错: $e', tag: 'PushNotification');
    // }
  }

  // addScrollListener() {
  //   // clog(scrollController.position.pixels);
  //   double offset = scrollController.offset;
  //   if (offset <= 50) {
  //     // 小于等于 50 不处理
  //     if (appBarOpacity.value != 0.0) {
  //       appBarOpacity.value = 0;
  //       // setState(() => _appBarOpacity = 0.0);
  //     }
  //   } else if (offset > 50 && offset <= 150) {
  //     // 50~150 范围线性插值透明度
  //     double opacity = (offset - 50) / 100;
  //
  //     appBarOpacity.value = opacity.clamp(0.0, 1.0);
  //   } else {
  //     // 超过 150 保持最大透明度
  //     if (appBarOpacity.value != 1.0) {
  //       appBarOpacity.value = 1.0;
  //     }
  //   }
  // }

  void loadData() async {
    Map<String, dynamic> params = {
      'page': page,
      'limit': limit,
    };
    try {
      if (page == 1) {
        refreshController.resetNoData();
      }
      
      final response = await HttpManager().get(
        API.getHomeList,
        params: params,
        fromJson: ModelHome.fromJson,
      );
      
      if (response.data is ModelHome) {
        homeModelRx.value = response.data;
      }
      
      if (page == 1) {
        // getHomeList1(); // 不需要await结果
        refreshController.refreshCompleted();
      } else {
        if (homeModelRx.value.list != null && homeModelRx.value.list!.isNotEmpty) {
          refreshController.loadComplete();
        } else {
          refreshController.loadNoData();
        }
      }
    } catch (e) {
      clog('首页请求异常：$e');
      if (page == 1) {
        refreshController.refreshFailed();
      } else {
        refreshController.loadFailed();
      }
    }
  }

  // void getHomeList1() async {
  //   try {
  //     final response = await HttpManager().get(
  //       API.getHomeList1,
  //       fromJson: ModelHome.fromJson,
  //     );
  //
  //     if (response.data is ModelHome) {
  //       homeModel1Rx.value = response.data;
  //     }
  //   } catch (e) {
  //     clog('轮播图异常：$e');
  //   }
  // }

  /// 打开分享界面
  void openShareAndScreenshot(int index) {
    // 这里临时添加一个空实现，避免在首页调用时出错
    LoadingUtils.showToast('分享功能开发中');
  }

  @override
  void onClose() {
    super.onClose();
    refreshController.dispose();
    // scrollController.removeListener(addScrollListener);
    // scrollController.dispose();
  }
}
